package com.dream.app.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dream.app.cache.AppCodeCache;
import com.dream.app.service.AppService;
import com.dream.dao.base.AppCodeDAO;
import com.dream.dao.base.AppCodeItemDAO;
import com.dream.model.app.AppAbstractUser;
import com.dream.model.app.AppCode;
import com.dream.model.app.AppCodeItem;
import com.dream.utils.hibernate.PagingVO;
import com.dream.vo.app.AppCodeVO;

/**
 * 
 * @author EvanYu
 *
 */
@Service("AppService")
public class AppServiceImpl implements AppService {

	@Autowired
	private AppCodeDAO appCodeDAO;
	
	@Autowired
	private AppCodeItemDAO appCodeItemDAO;
	
	@Autowired
	private AppCodeCache appCodeCache;
	
	@Override
	@Transactional
	public PagingVO queryAppCode(AppCodeVO vo, PagingVO pageVO) {
		return appCodeDAO.query(vo, pageVO);
		
	}

	@Override
	@Transactional
	public PagingVO queryAppCodeItem(AppCodeVO vo, PagingVO pageVO) {
		
		return appCodeItemDAO.query(vo, pageVO);
	}

	@Override
	@Transactional
	public void updateAppCodeItem(AppCodeVO vo, AppAbstractUser user) {
		
		AppCodeItem item = new AppCodeItem();
		if(vo.getId() != null){
			item = appCodeItemDAO.selectById(vo.getId());
			vo.populate(item);
			item.setUpdateTime(new Date());
			item.setUpdateUser(user.getId());
			appCodeItemDAO.saveOrUpdate(item);
		}else{
			vo.populate(item);
			item.setCreateTime(new Date());
			item.setCreateUser(user.getId());
			appCodeItemDAO.save(item);
		}
		reloadCache(item.getAppCodeId());
		
	}

	@Override
	@Transactional
	public void deleteAppCodeItem(Long id, AppAbstractUser user) {
		
		AppCodeItem item = appCodeItemDAO.selectById(id);	
		item.setUpdateTime(new Date());
		item.setUpdateUser(user.getId());
		item.setDeleted(true);
		appCodeItemDAO.saveOrUpdate(item);
		reloadCache(item.getAppCodeId());
		
	}
	
	private void reloadCache(Long id){
		
		AppCode appcode = appCodeDAO.selectById(id);
		if(appcode != null)
		appCodeCache.reload(appcode.getName());
	}
	
	

}
